import os
import sys
from pathlib import Path
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from app.utils.password import hash_password
from app.db.db_models import Base, User, Number

# 添加项目根目录到 Python 路径
BASE_DIR = Path(__file__).parent.parent
sys.path.append(str(BASE_DIR))

# 数据库路径
DB_PATH = os.path.join(BASE_DIR, 'app', 'db', 'app.db')

def init_database():
    """初始化数据库，创建必要的表和测试数据"""
    print(f"在以下位置创建数据库: {DB_PATH}")
    
    # 确保数据库目录存在
    os.makedirs(os.path.dirname(DB_PATH), exist_ok=True)
    
    # 创建数据库引擎
    engine = create_engine(f"sqlite:///{DB_PATH}", connect_args={"check_same_thread": False})
    
    # 创建所有表
    Base.metadata.create_all(engine)

    # 创建会话
    SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
    db = SessionLocal()

    # 插入测试用户数据
    test_users = [
        {
            'username': 'john',
            'email': 'johndoe@example.com',
            'full_name': 'John Doe',
            'disabled': False,
            'password': 'secret'
        },
        {
            'username': 'alice',
            'email': 'alice@example.com',
            'full_name': 'Alice Wonderson',
            'disabled': True,
            'password': 'secret2'
        },
        {
            'username': 'testuser',
            'email': 'test@example.com',
            'full_name': 'Test User',
            'disabled': False,
            'password': 'testpassword'
        }
    ]

    # 插入用户
    for user in test_users:
        try:
            hashed_password = hash_password(user['password'])
            new_user = User(
                username=user['username'],
                email=user['email'],
                full_name=user['full_name'],
                disabled=user['disabled'],
                hashed_password=hashed_password
            )
            db.add(new_user)
        except Exception as e:
            print(f"用户 {user['username']} 已存在或插入失败: {e}")

    db.commit()

    # 初始化一些测试数字
    test_numbers = [42, 100, 200, 300]
    for number in test_numbers:
        new_number = Number(value=number)
        db.add(new_number)

    db.commit()
    db.close()

if __name__ == '__main__':
    print("正在初始化数据库...")
    init_database()
    print("数据库初始化完成！") 